package com.jiaoyou.baojian;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.notification.BasicCustomPushNotification;
import com.alibaba.sdk.android.push.notification.CustomNotificationBuilder;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.google.gson.Gson;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.entity.response.LoginResponse;
import com.jiaoyou.baojian.utils.ACache;
import com.jiaoyou.baojian.utils.Utils;
import com.liulishuo.filedownloader.FileDownloader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by DemonZYM on 17/4/12.
 */

public class BaojianApplication extends Application {

    {
        PlatformConfig.setWeixin(ConstValue.WEIXIN_APPID, ConstValue.WEIXIN_APPSECRET);
    }

    private static BaojianApplication instance;
    public static BaojianApplication getInstance(){
        return instance;
    }
    private final IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, null);

    private final String TAG = "BaojianApplication";
    public CloudPushService pushService;
    public boolean pushServiceStarted = false;
    private AgoraHelper agoraHelper;

    private Timer timer;
    private long BACKGROUND_TIMER_PERIOD = 1000;

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;
        initCloudChannel();
        initUmeng();
        initAgora();
        regWX();
        FileDownloader.init(this);
    }

    public void stayOnline() {
        Log.e("stayOnline", "stayOnline");
        if(timer == null) {
            timer = new Timer();
            timer.schedule(timerTask, BACKGROUND_TIMER_PERIOD * 10, BACKGROUND_TIMER_PERIOD * 60 * 3);
        }
    }

    private void initAgora() {
        AgoraHelper.getInstance().init();
        agoraHelper = AgoraHelper.getInstance();
    }

    public AgoraHelper getAgoraHelper(){
        return agoraHelper;
    }

    /**
     * 初始化云推送通道
     */
    private void initCloudChannel() {
        PushServiceFactory.init(this);
        pushService = PushServiceFactory.getCloudPushService();
        pushService.turnOffPushChannel(null);
        pushService.register(this, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success");
                pushServiceStarted = true;
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });

        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
        MiPushRegister.register(this, ConstValue.XIAOMI_PUSH_APPID, ConstValue.XIAOMI_PUSH_APPKEY);
        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
        HuaWeiRegister.register(this);

        BasicCustomPushNotification notification = new BasicCustomPushNotification();
        notification.setNotificationFlags(Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL);
        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_SOUND);
        notification.setStatusBarDrawable(R.drawable.icon_small);
        notification.setServerOptionFirst(true);
//        notification.setBuildWhenAppInForeground(false);
        boolean res = CustomNotificationBuilder.getInstance().setCustomNotification(1, notification);
    }

    public void turnOnPush(){
        pushService.turnOnPushChannel(new CommonCallback() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onFailed(String s, String s1) {

            }
        });
    }

    public void turnOffPush(){
        pushService.turnOffPushChannel(new CommonCallback() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onFailed(String s, String s1) {

            }
        });
    }

    private void regWX() {
        iwxapi.registerApp(ConstValue.WEIXIN_APPID);
    }
    public IWXAPI getWXApi(){
        return iwxapi;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initUmeng() {
        UMShareAPI.get(this);
        MobclickAgent.setDebugMode(BuildConfig.DEBUG);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
    }

    private TimerTask timerTask = new TimerTask(){
        @Override
        public void run() {
            Log.e("timerTask", "check is online");
            if(!Utils.isLogin())
                return;
            if(!BaojianApplication.getInstance().getAgoraHelper().isLogin){
                Log.e("timerTask", "re login");
                //信令登录因未知原因被断开，自动重新登录
                LoginResponse loginResponse =
                        new Gson().fromJson(ACache.get(BaojianApplication.getInstance()).getAsString(LoginResponse.TAG),
                                LoginResponse.class);
                final String account = loginResponse.user.id + "";
                AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, Utils.getAgoraToken(account), 0, "");
                return;
            }
            try {
                if (Utils.isRunningForeground()) {
                    Log.e("timerTask", "forground");
                    AgoraHelper.getInstance().setForground();
                } else {
                    Log.e("timerTask", "background");
                    AgoraHelper.getInstance().setBackground();
                }
            } catch (Exception e){}
        }
    };
}
